/*
 *  Copyright (C) 2010 takaji
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package examples;

import dakside.csv.CSVException;
import dakside.csv.CSVFileReader;
import dakside.csv.CSVLine;
import examples.helpers.CSVDump;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Example 1: read CSV line-by-line
 * @author takaji
 */
public class Example1 {

    /**
     * read CSV line-by-line
     * @param filename
     */
    public static void testReadEachLine(String filename) {
        // try to parse each line
        try {
            System.out.println("Sample 1: Reading CSV file line by line.");
            System.out.println("This is very useful when "
                    + "you want to parse a csv file line by line ...");

            //1. Open file
            System.out.println("Opening file " + filename);
            CSVFileReader csvReader = new CSVFileReader(filename);
            System.out.println("--------------------------");
            //declare a tempotary CSVLine object (each line)
            CSVLine tempLine = null;
            //read each line in CSV file
            while ((tempLine = csvReader.readLine()) != null) {
                //Do something process with the line
                //e.g. Write to screen
                CSVDump.dumpLineText(tempLine);
            }
            System.out.println("--------------------------");
            System.out.println("EOF.");
            //Remember to close the file after use
            csvReader.close();
        } catch (CSVException ex) {
            Logger.getLogger(Example4.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @param args  the command line arguments
     */
    public static void main(String[] args) {
        // first argument is file name
        // we should have 1 argument here
        if (args.length != 1) {
            System.out.println("Usage:");
            System.out.println("java -jar dakside.csv.jar /path/to/file.csv");
            return;
        }

        String filename = args[0];
        //Test read each line in chosen CSV file.
        testReadEachLine(filename);

        System.out.println("Finished.");
    }
}
